package com.xj.edu.hotel.controller;

import com.xj.edu.hotel.domain.User;
import com.xj.edu.hotel.service.LoginService;
import com.xj.edu.hotel.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpSession;
import java.util.Random;

@Controller
@RequestMapping("/userLogin")
public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private MailService mailService;

    private String validataCheckCode=null;

    /**
     * 用户登录
     */
    @RequestMapping("/login")
    public String login(User user, Model model,HttpSession session ) {
        System.out.println(user.getUserName());
       User user1 = loginService.findByName(user);
        if (user1 != null) {
            if (user.getUserPassword().equals(user1.getUserPassword())) {
                //model.addAttribute("user", user1);
                session.setAttribute("user",user1);
                return "redirect:/toUserLogin";
            } else {
                //model.addAttribute("msg", "密码错误");
                return "redirect:/toUserLogin";
            }
        } else {
           // model.addAttribute("msg", "用户不存在");
            return "redirect:/toUserLogin";
        }
    }
    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/toUserLogin";
    }
    /**
     * 忘记密码
     */
    @RequestMapping("forgetPassword")
    @ResponseBody
    public String forgetPassword(String userEmail,String userPassword,String checkCode){
        if (checkCode.equals(validataCheckCode)){
            //通过邮箱查找
           User user = loginService.findByEmail(userEmail);
           if (user != null){
               loginService.updatePassword(userEmail,userPassword);
               return "ok";
           }else {
               return "UnKnowAccount";
           }
        }else {
            return "error";
        }
    }

    /**
     * 获取验证码
     */
    @RequestMapping("getCheckCode")
    @ResponseBody
    public String getCheckCode(String email){
        String checkCode = String.valueOf(new Random().nextInt(899999)+100000);
        validataCheckCode = checkCode;
        String message = "您的验证码"+checkCode;
        System.out.println(checkCode);
        try {
            mailService.sendSimpleMail(email,"验证码",message);
        }catch (Exception e){
            return "";
        }
        return checkCode;
    }


}





